﻿
package extremefx.gis {
	import flash.geom.Point;
	import flash.geom.Rectangle;		

	/**
	 * @author Marcelo Volmaro
	 */
	public final class GeoReference {
		private var _points:Vector.<Coord>;
		private var _lat0:Number;
		private var _long0:Number;
		private var _deltaX:Number;
		private var _deltaY:Number;

		/**
		 * @param pPoints an array of <code>Coord<code> points to be mapped into/from pixels.
		 * @param pBoundingBox the bounding box used to map coordinates to pixels. 
		 */
		public function GeoReference(pPoints:Vector.<Coord>, pBoundingBox:Rectangle) {
			_points = pPoints;
			
			var minLat:Number, minLong:Number, maxLat:Number, maxLong:Number;
			minLat = minLong = Number.MAX_VALUE;
			maxLat = maxLong = Number.MIN_VALUE;
			
			for each (var coord:Coord in pPoints){
				minLat = Math.min(minLat, coord.latitude);
				minLong = Math.min(minLong, coord.longitude);
				maxLat = Math.max(maxLat, coord.latitude);
				maxLong = Math.max(maxLong, coord.longitude);
			}
			
			_deltaX = (maxLong - minLong) / (pBoundingBox.height);
			_deltaY = (minLat - maxLat) / (-pBoundingBox.width);
			
			_lat0 = maxLat - pBoundingBox.bottom * _deltaY;
			_long0 = minLong - pBoundingBox.left * _deltaX;
		}
		
		/**
		 * Converts X and Y pixel coordinates to Latitude and Longitude coordinates
		 * @param pPoint the pixel coordinate to convert
		 * @return a <code>Coord</code> object positioned at the converted pixel coordinates
		 */
		public function xyToLatLong(pPoint:Point):Coord {
            return new Coord(_lat0 + _deltaY * pPoint.y, _long0 + _deltaX * pPoint.x);
		}
		
		/**
		 * Converts Latitude and Longitude to X and Y pixels
		 * @param pCoord the coordinate to convert to pixels
		 * @return a <code>Point</code> object positioned at the converted latitude/longitude coordinates
		 */
		public function latLongToXY(pCoord:Coord):Point {
			return new Point((pCoord.longitude - _long0) / _deltaX, (pCoord.latitude - _lat0) / _deltaY);
		}
	}
}
